package com.wzm.moviepic.fragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import android.widget.TextView;


import com.wzm.bean.AdInfo;
import com.wzm.bean.PicInfo;
import com.wzm.cache.ConfigCache;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.moviepic.R;
import com.wzm.utils.Logger;


public class AdMainFragment extends Fragment{

    //广告    
    private ViewPager adpager = null;
    private MyAdapter adAdapter = null;
    private int currentItem = 0;
    private ScheduledExecutorService scheduledExecutorService;
    
    private ArrayList<AdInfo> adList = new ArrayList<AdInfo>();
    
    private FinalBitmap fb = null;
    private FinalHttp fh = null;
    
    private Context mContext = null;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		mContext = getActivity();
		
		View view = inflater.inflate(R.layout.fragment_main_ad, null);
		adpager = (ViewPager)view.findViewById(R.id.adpager);
		
		
		 //初始化HTTP，网络图片组件
        fh = AppManager.getInstance(getActivity()).getFh();		
		fb = FinalBitmap.create(getActivity(),Environment.getExternalStorageDirectory().getPath()+AppConfig.IMGCACHE);
		fb.configLoadingImage(R.drawable.spic);
		fb.configLoadfailImage(R.drawable.spic);
		
		//广告
		adAdapter = new MyAdapter();
		adpager.setAdapter(adAdapter);// 设置填充ViewPager页面的适配器
		getAdList();
		
		
		return view;
	}
	
	// 切换当前显示的图片
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			adpager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};
    
	/**
	 * 换行切换任务
	 * 
	 * @author Administrator
	 * 
	 */
	private class ScrollTask implements Runnable {

		public void run() {
			synchronized (adpager) {
				if(adList.size()!=0)
				{
					//Logger.info("currentItem: " + currentItem);
					currentItem = (currentItem + 1) % adList.size();
					handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
				}				
			}
		}

	}
	
	@Override
	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 4, TimeUnit.SECONDS);
		
		super.onStart();
	}
    
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		//Logger.error("广告滚动停止");
		scheduledExecutorService.shutdown();
		super.onStop();
	}
	
	//获取广告列表
	public void getAdList()
	{
		Logger.info("getAdList");
		//WIFI,4个小时，MOBILE 6个小时
		String AdCachelist = ConfigCache.getUrlCache(AppConfig.ADURL,0*60*60*1000,0*60*60*1000);
		if(AdCachelist==null)
		{//重新获取
			//Logger.info("111111111");
			AjaxParams params = new AjaxParams();
    		params.put("platform","Android");
    		fh.post(AppConfig.ADURL, params,new AjaxCallBack<Object>() {

				@Override
				public void onSuccess(Object t) {
					// TODO Auto-generated method stub
					super.onSuccess(t);
					String json = t.toString();
					Logger.info("ad:"+json);
					ConfigCache.setUrlCache(json, AppConfig.ADURL);	
					excuteAdJson(json);
				}

				@Override
				public void onFailure(Throwable t, String strMsg) {
					// TODO Auto-generated method stub
					super.onFailure(t, strMsg);
					Logger.error("aderror:"+strMsg);
				}
    			
			});
    		params = null;
		}else{
			//Logger.info("222222222");
			excuteAdJson(AdCachelist);
		}
	}
	
	public void excuteAdJson(String json)
	{
		try {
			JSONObject obj = new JSONObject(json);
			int status = obj.getInt("status");
			if(status==1)
			{
				adList.clear();
				JSONArray alist = obj.getJSONArray("top");
				for(int i=0;i<alist.length();i++)
				{
					JSONObject item = alist.getJSONObject(i);
					AdInfo adinfo = new AdInfo();
					adinfo.setId(item.getString("id"));
					adinfo.setImage(item.getString("image"));
					adinfo.setApp_type(item.getString("app_type"));
					adinfo.setName(item.getString("name"));
					adinfo.setCompany(item.getString("company"));
					adinfo.setIcon(item.getString("icon"));
					adinfo.setScore(item.getString("score"));
					adinfo.setIntro(item.getString("intro"));
					adinfo.setTop_img(item.getString("top_img"));
					adinfo.setCell_img(item.getString("cell_img"));
					List<String> mlist = new ArrayList<String>();
					JSONArray slist = item.getJSONArray("screenshots");
				    
					for(int ii=0;ii<slist.length();ii++)
					{
						String sitem = slist.getString(ii);
						//Logger.info(sitem);
						mlist.add(sitem);
					}
					adinfo.setMlist(mlist);
					mlist = null;
					adinfo.setOpen_url(item.getString("open_url"));
					adinfo.setOpen_url_title(item.getString("open_url_title"));
					adinfo.setWebsite(item.getString("website"));
					adinfo.setEmail(item.getString("email"));
					adinfo.setShow_details(item.getString("show_details"));
					List<PicInfo> advpics = new ArrayList<PicInfo>();
					JSONArray advlist = item.getJSONArray("adv_pics");
					for(int j=0;j<advlist.length();j++)
					{
						JSONObject picinfoitem = advlist.getJSONObject(i);
						PicInfo pi = new PicInfo();
						pi.setId(picinfoitem.getString("id"));
						pi.setpIndex(picinfoitem.getString("index"));
						pi.setImage(picinfoitem.getString("image"));
						pi.setIntro(picinfoitem.getString("intro"));
						pi.setScript(picinfoitem.getString("script"));
						advpics.add(pi);
						pi = null;
					}					
					adList.add(adinfo);	
					adinfo = null;
				}
				
				Logger.info("广告请求完毕："+adList.size());
				adAdapter.notifyDataSetChanged();
				//adtitle.setText(adList.get(0).getName());
			}
			
			obj = null;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			Logger.error(e.getMessage());
		}
	}
	
	 /**
		 * 填充广告模块ViewPager页面的适配器
		 * 
		 * @author Administrator
		 * 
		 */
		private class MyAdapter extends PagerAdapter {
			private LayoutInflater  mInflater;
			
			MyAdapter()
			{
				mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);	
			}
			@Override
			public int getCount() {
				return adList.size();
			}
			

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				
				final AdInfo adinfo = adList.get(position);
				
				View view = mInflater.inflate(R.layout.ad_item, container, false);   
				
				
				ImageView adImage = (ImageView)view.findViewById(R.id.ad_img);
				adImage.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						String showDetail = adinfo.getShow_details();
						if(showDetail.equals("0"))
						{//打开链接
							Uri uri = Uri.parse(adinfo.getOpen_url());  
							Intent it = new Intent(Intent.ACTION_VIEW, uri);  
							startActivity(it);
						}else if(showDetail.equals("1"))
						{//打开详细页面
							Uri uri = Uri.parse(adinfo.getOpen_url());  
							Intent it = new Intent(Intent.ACTION_VIEW, uri);  
							startActivity(it);
						}
					}
				});
				//adImage.setScaleType(ScaleType.FIT_XY);
				fb.display(adImage, adinfo.getCell_img());				
				TextView tv_title = (TextView)view.findViewById(R.id.ad_title);
				tv_title.setText(adinfo.getName());
				return view;
			}

			@Override
			public void destroyItem(View arg0, int arg1, Object arg2) {
				((ViewPager) arg0).removeView((View) arg2);
			}

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0 == arg1;
			}

			@Override
			public void restoreState(Parcelable arg0, ClassLoader arg1) {

			}

			@Override
			public Parcelable saveState() {
				return null;
			}

			@Override
			public void startUpdate(View arg0) {

			}

			@Override
			public void finishUpdate(View arg0) {

			}
		}
	
}
